/*
 * @Author: fishroom
 * @Date: 2022-09-28 13:34:17
 * @LastEditTime: 2022-10-13 14:02:11
 * @FilePath: \koa\app\db\index.ts
 */
import path from "path";
import { Sequelize } from "Sequelize-typescript";
import config from "../config/db";
import { dbLogger } from "../logger";

// 方法 3: 分别传递参数 (其它数据库)
const sequelize = new Sequelize(
  config.db_name as string,
  config.db_user as string,
  config.db_password as string,
  {
    host: config.db_host as string,
    dialect: "mysql",
    port: config.db_port as unknown as number,
    models: [
      path.join(__dirname, "..", "model/**/*.ts"),
      path.join(__dirname, "..", "model/**/*.js"),
    ],
    logging: (msg) => {
      dbLogger.info(msg);
    },
    // 设置映射字段
    define: {
      timestamps: true,
      createdAt: "created_at",
      updatedAt: "updated_at",
      deletedAt: "deleted_at",
      freezeTableName: true,
    },
  }
);
const db = async () => {
  try {
    await sequelize.authenticate();
    console.log("Connection has been established successfully.");
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  }
};
export default db;
